package org.openaltimeter.desktopapp;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeAxisFormat extends NumberFormat 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private DecimalFormat decimalFormater;
	private SimpleDateFormat dateFormater;
	
	private TimeAxisFormatType actualFormater;
	
	public TimeAxisFormat()
	{
		this.decimalFormater = new DecimalFormat();
		this.dateFormater = new SimpleDateFormat();
		
		this.actualFormater = TimeAxisFormatType.HOUR_TYPE;
	}
	
	public void setFormatType(TimeAxisFormatType type)
	{
		this.actualFormater = type;	
	}
	
	@Override
	public StringBuffer format(double number, StringBuffer toAppendTo,
			FieldPosition pos) 
	{
		if (actualFormater == TimeAxisFormatType.HOUR_TYPE)
		{
			String format = "mm:ss";
			if (number > 3600)
				format = "H:" + format;
			
			dateFormater.applyPattern(format);
			long offset = Calendar.getInstance().getTimeZone().getOffset((long) (number * 1000)); 
			Date date = new Date((long) (number * 1000) - offset);
			
			StringBuffer formatedValue = dateFormater.format(date, toAppendTo, pos);

			if ((long) (number * 10) % 10 > 0)
				formatedValue.append('.').append((long) (number * 10) % 10);
			
			return formatedValue;
		}
		else
			return decimalFormater.format(number, toAppendTo, pos);
	}

	@Override
	public StringBuffer format(long number, StringBuffer toAppendTo,
			FieldPosition pos) 
	{
		return this.format((double) number, toAppendTo, pos);
	}

	@Override
	public Number parse(String source, ParsePosition parsePosition) 
	{
		if (actualFormater == TimeAxisFormatType.HOUR_TYPE)
		{
			Date parsedValue = dateFormater.parse(source, parsePosition);
			return parsedValue.getTime() / 1000;
		}
		else
			return decimalFormater.parse(source, parsePosition);
	}
	
}
